﻿using System.Data.SqlClient;
using System;
using System.Messaging;
using System.Data;
using Entity;
namespace WindowsService1
{
    partial class Service1
    {
        /// <summary> 
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源，为 true；否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 组件设计器生成的代码

        /// <summary> 
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            // 
            // Service1
            // 
            this.ServiceName = "Web_Logs";
            this.timer1 = new System.Timers.Timer();
            //  ((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
            this.timer1.Start();
            this.timer1.Interval = 1000;
            this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);


        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            MessageQueueService.Start();
        }

        #endregion


    }

    /// <summary>
    /// 接收来自MSMQ的消息，并保存到数据库
    /// </summary>
    public class MessageQueueService
    {
        public static bool blnStopThread;
        public static string exTemp = string.Empty;

        public MessageQueueService()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        public static void Start()
        {
            string queuePath = ".\\Private$\\zzl";
            IsQueueExists(queuePath);
            MessageQueue myQueue = new MessageQueue(queuePath);

            myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(Web_Logs) });

            do
            {
                try
                {
                    // Receive and format the message.
                    Message myMessage = myQueue.Receive(); //当消息队列空时，线程会挂起
                    Web_Logs log = (Web_Logs)myMessage.Body;

                    if (log == null) return;

                    Save(log);//保存到数据库，此处略详细代码
                }
                catch (System.Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            } while (blnStopThread == false);
        }

        private static void IsQueueExists(string path)
        {
            if (!MessageQueue.Exists(path))
            {
                MessageQueue.Create(path);
            }
        }

        private static void Save(Web_Logs entity)
        {
            using (SqlConnection sqlconn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ToString()))
            {
                using (SqlCommand sqlcomm = new SqlCommand(
                    "INSERT INTO [Web_Logs]([LogID],[FromURL],[ExeSQL],[FromSystem],[HttpMethod],[OccurTime],[info]) VALUES (@LogID,@FromURL,@ExeSQL,@FromSystem,@HttpMethod,@OccurTime,@Info);"
                    , sqlconn))
                {


                    SqlParameter parameter = new SqlParameter("@LogID", SqlDbType.VarChar, 36);
                    parameter.Value = entity.LogID;
                    sqlcomm.Parameters.Add(parameter);

                    parameter = new SqlParameter("@FromURL", SqlDbType.VarChar, 200);
                    parameter.Value = entity.FromURL;
                    sqlcomm.Parameters.Add(parameter);

                    parameter = new SqlParameter("@ExeSQL", SqlDbType.VarChar, 1000);
                    parameter.Value = entity.ExeSQL;
                    sqlcomm.Parameters.Add(parameter);

                    parameter = new SqlParameter("@FromSystem", SqlDbType.Int);
                    parameter.Value = entity.FromSystem;
                    sqlcomm.Parameters.Add(parameter);

                    parameter = new SqlParameter("@HttpMethod", SqlDbType.VarChar, 50);
                    parameter.Value = entity.HttpMethod;
                    sqlcomm.Parameters.Add(parameter);

                    parameter = new SqlParameter("@Info", SqlDbType.NVarChar, 4000);
                    parameter.Value = entity.Info;
                    sqlcomm.Parameters.Add(parameter);

                    parameter = new SqlParameter("@OccurTime", SqlDbType.DateTime);
                    parameter.Value = entity.OccurTime;
                    sqlcomm.Parameters.Add(parameter);

                    sqlconn.Open();
                    sqlcomm.ExecuteNonQuery();
                    sqlconn.Close();
                }
            }
        }
    }

}
